package logic

import (
	"fmt"
	"gitee.com/DonHz/qimi/bluebell/dao/mysql"
	"gitee.com/DonHz/qimi/bluebell/models"
	"gitee.com/DonHz/qimi/bluebell/util/encrypt"
	"gitee.com/DonHz/qimi/bluebell/util/snowflake"
)

func SignUp(req models.SignUpParams) (err error){
	//1.判断用户是否存在
	var exist bool
	exist, err = mysql.CheckUserExist(req.Name)
	fmt.Println(exist)
	if err!=nil{
		// 数据库查询出错
		return err
	}
	if exist {
		return mysql.ErrorUserExist
	}
	//2.生成UID
	userId:= snowflake.GenID()
	user:=&models.User{
		UserId: userId,
		Name: req.Name,
		Password: req.Password,
		Email: req.Email,
		Gender: GenderStringToInt(req.Gender),
	}
	//3. 保存到数据库
	err = mysql.Insert(user)
	return err
}

func Login(req *models.LoginParams) (int64, error) {
	u:=&models.User{
		Name: req.Name,
		Password: encrypt.EncryptPassword(req.Password),
	}
	// 传递的是指针 能拿到userId
	if err:=mysql.Login(u); err!=nil {
		return 0, err
	}
	return u.UserId, nil
}

func GenderStringToInt(gender string) int8 {
	if gender=="男" {
		return 1
	}
	if gender=="女" {
		return 2
	}
	return 0
}